#include "../GameLogic/GameManager.h"
#include "PutGameLayer.h"
#include "HeadLayer.h"


using namespace cocos2d;

bool PutGameLayer::OnInit()
{
	SetZOrder(1);
	setContentSize(CCSize(740,1060));
	setTouchEnabled(true);
	CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("qiuheti/item2.plist");
	CCSize size = CCDirector::sharedDirector()->getWinSize();
	mMainBkground = CCSprite::create("qiuheti/bg_main.png");
	if(!mMainBkground)
		return false;
	mMainBkground->setAnchorPoint(ccp(0.0f,0.0f));
	mMainBkground->setPosition(ccp(0,0));
	this->addChild(mMainBkground, 0);
	GGameMgr->GetMapGridMgr()->SetCurrentLayer(this);
	setVisible(true);
	GGameMgr->GetPutItemManager()->SetGrid(NULL);
	Flush();
	return true;
}

void PutGameLayer::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
	CCSetIterator iter = pTouches->begin();
	CCTouch* touch = (CCTouch*)*iter;
	CCPoint pt = touch->getLocation();

	pt.x = pt.x/GGameMgr->GetScaleX();
	pt.y = pt.y/GGameMgr->GetScaleY();

	CCLOG("Click Index is %d",GGameMgr->GetMapGridMgr()->GetIndexFromPostion(pt));
	MapGrid* pGrid = GGameMgr->GetMapGridMgr()->GetMapGridFromPostion(pt);

	GGameMgr->GetMapGridMgr()->ResetGrids();

	if(!pGrid||pGrid->mItemId!=EII_NULL)
	{
		GGameMgr->GetPutItemManager()->SetGrid(NULL);
		Flush();
		return ;
	}
	if(!GGameMgr->GetPutItemManager()->SetGrid(pGrid))
	{
		pGrid->mItemId=GGameMgr->GetPutItemManager()->GetNowItem();
		WORD buffer[36];
		std::list<WORD> tmparr;
		GGameMgr->GetMapGridMgr()->InitTestCombination(buffer,36);
		GGameMgr->GetMapGridMgr()->TestCombination(buffer,36,pGrid->mIndex,pGrid->mItemId,&tmparr);
		if(tmparr.size()>=3)
		{
			for(std::list<WORD>::iterator iter=tmparr.begin();iter!=tmparr.end();++iter)
			{
				WORD index = *iter;
				MapGrid* pg = GGameMgr->GetMapGridMgr()->GetGridByIndex(index);
				if(pg==pGrid)
					continue;
				CCPoint delpt;
				delpt.x = pGrid->getPosition().x - pg->getPosition().x;
				delpt.y = pGrid->getPosition().y - pg->getPosition().y;
				delpt.x = delpt.x*5/sqrt(delpt.x*delpt.x+delpt.y*delpt.y);
				delpt.y = delpt.y*5/sqrt(delpt.x*delpt.x+delpt.y*delpt.y);
				CCMoveBy* mv = CCMoveBy::create(0.3f,delpt);
				CCMoveBy* mvr = (CCMoveBy*)mv->reverse();
				CCSequence* seq = (CCSequence*)CCSequence::create(mv,mvr,NULL);
				pg->aSpr->runAction(CCRepeatForever::create(seq));
			}
		}
		pGrid->mItemId=EII_NULL;
		Flush();
	}
	else
	{
		GGameMgr->GetPutItemManager()->SetGrid(NULL);
		GGameMgr->GetPutItemManager()->PutItemToGrid(this,pGrid);
	}
}

void PutGameLayer::Flush()
{
	HeadLayer* headlayer = (HeadLayer*)GameSceneMgr::Instance()->GetNowScene()->GetGameLayer(CSString("layer_head"));
	headlayer->Flush();
	GGameMgr->GetMapGridMgr()->DrawAllItemBack();
}